<!-- <template>
<div>
    group
</div>  
</template>
<script setup>

</script>


<style scoped>

</style> -->



<template>
    <div class="app-container">
      <!-- 操作栏 -->
      <div class="mb-4">
        <el-button type="primary" @click="handleAdd">新增菜单</el-button>
        <el-button @click="expandAll">全部展开</el-button>
        <el-button @click="collapseAll">全部折叠</el-button>
      </div>
  
      <!-- 菜单表格 -->
      <el-table
        ref="menuTable"
        :data="menuData"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        border
        default-expand-all
      >
        <el-table-column prop="title" label="菜单名称" width="220">
          <template #default="{ row }">
            <i v-if="row.icon" :class="row.icon" class="mr-2" />
            {{ row.title }}
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路由路径" width="180" />
        <el-table-column prop="permission" label="权限标识" width="180" />
        <el-table-column label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.type === 1 ? 'primary' : 'success'">
              {{ row.type === 1 ? '菜单' : '按钮' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="100" sortable />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 菜单编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑菜单' : '新增菜单'"
        width="600px"
      >
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="100px"
        >
          <el-form-item label="父级菜单" prop="parentId">
            <el-cascader
              v-model="formData.parentId"
              :options="menuOptions"
              :props="cascaderProps"
              clearable
              placeholder="请选择父级菜单"
            />
          </el-form-item>
          <el-form-item label="菜单类型" prop="type">
            <el-radio-group v-model="formData.type">
              <el-radio-button :label="1">菜单</el-radio-button>
              <el-radio-button :label="2">按钮</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="菜单名称" prop="title">
            <el-input v-model="formData.title" />
          </el-form-item>
          <el-form-item label="路由路径" prop="path" v-if="formData.type === 1">
            <el-input v-model="formData.path" />
          </el-form-item>
          <el-form-item label="权限标识" prop="permission">
            <el-input v-model="formData.permission" />
          </el-form-item>
          <el-form-item label="菜单图标" prop="icon">
            <el-input v-model="formData.icon">
              <template #prefix>
                <i v-if="formData.icon" :class="formData.icon" class="mr-2" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="排序号" prop="sort">
            <el-input-number v-model="formData.sort" :min="0" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit"> 确认 </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, computed, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  
  // 模拟初始数据
  const menuData = ref([
    {
      id: 1,
      title: '系统管理',
      icon: 'el-icon-s-tools',
      path: '/system',
      type: 1,
      permission: 'system:manage',
      sort: 1,
      status: 1,
      children: [
        {
          id: 11,
          title: '用户管理',
          icon: 'el-icon-user',
          path: '/system/user',
          type: 1,
          permission: 'system:user',
          sort: 1,
          status: 1
        },
        {
          id: 12,
          title: '菜单管理',
          icon: 'el-icon-menu',
          path: '/system/menu',
          type: 1,
          permission: 'system:menu',
          sort: 2,
          status: 1
        }
      ]
    }
  ])
  
  // 对话框相关状态
  const dialogVisible = ref(false)
  const isEdit = ref(false)
  const formRef = ref(null)
  const formData = ref(getDefaultFormData())
  const menuTable = ref(null)
  
  // 级联选择器配置
  const cascaderProps = {
    checkStrictly: true,
    value: 'id',
    label: 'title',
    children: 'children',
    emitPath: false
  }
  
  // 生成菜单选项（过滤自身）
  const menuOptions = computed(() => {
    return generateMenuOptions(menuData.value)
  })
  
  // 表单验证规则
  const formRules = {
    title: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
    type: [{ required: true, message: '请选择菜单类型', trigger: 'change' }],
    permission: [{ required: true, message: '请输入权限标识', trigger: 'blur' }],
    sort: [{ required: true, message: '请输入排序号', trigger: 'blur' }]
  }
  
  // 获取默认表单数据
  function getDefaultFormData() {
    return {
      id: null,
      parentId: null,
      title: '',
      path: '',
      icon: '',
      type: 1,
      permission: '',
      sort: 0,
      status: 1
    }
  }
  
  // 生成级联选择器选项
  function generateMenuOptions(menus, parentId = null) {
    return menus
      .filter(menu => menu.id !== formData.value.id) // 过滤自身
      .map(menu => ({
        id: menu.id,
        title: menu.title,
        parentId: parentId,
        children: menu.children ? generateMenuOptions(menu.children, menu.id) : null
      }))
  }
  
  // 操作方法
  function handleAdd() {
    isEdit.value = false
    formData.value = getDefaultFormData()
    dialogVisible.value = true
  }
  
  function handleEdit(row) {
    isEdit.value = true
    formData.value = {
      ...row,
      parentId: findParentId(menuData.value, row.id)
    }
    dialogVisible.value = true
  }
  
  function findParentId(menus, targetId, parentId = null) {
    for (const menu of menus) {
      if (menu.id === targetId) return parentId
      if (menu.children) {
        const found = findParentId(menu.children, targetId, menu.id)
        if (found !== null) return found
      }
    }
    return null
  }
  
  function handleDelete(row) {
    ElMessageBox.confirm('确定要删除该菜单吗?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteMenu(menuData.value, row.id)
      ElMessage.success('删除成功')
    })
  }
  
  function deleteMenu(menus, id) {
    for (let i = 0; i < menus.length; i++) {
      if (menus[i].id === id) {
        menus.splice(i, 1)
        return true
      }
      if (menus[i].children && deleteMenu(menus[i].children, id)) {
        return true
      }
    }
  }
  
  function expandAll() {
    menuData.value.forEach(row => {
      menuTable.value.toggleRowExpansion(row, true)
    })
  }
  
  function collapseAll() {
    menuData.value.forEach(row => {
      menuTable.value.toggleRowExpansion(row, false)
    })
  }
  
  async function handleSubmit() {
    await formRef.value.validate()
    
    const newMenu = {
      ...formData.value,
      id: isEdit.value ? formData.value.id : Date.now()
    }
  
    if (isEdit.value) {
      updateMenu(menuData.value, newMenu)
    } else {
      addMenu(menuData.value, newMenu)
    }
  
    dialogVisible.value = false
    ElMessage.success('操作成功')
  }
  
  function updateMenu(menus, newMenu) {
    for (let i = 0; i < menus.length; i++) {
      if (menus[i].id === newMenu.id) {
        menus[i] = { ...newMenu }
        return true
      }
      if (menus[i].children && updateMenu(menus[i].children, newMenu)) {
        return true
      }
    }
  }
  
  function addMenu(menus, newMenu) {
    if (!newMenu.parentId) {
      menus.push(newMenu)
      return
    }
    
    for (const menu of menus) {
      if (menu.id === newMenu.parentId) {
        if (!menu.children) menu.children = []
        menu.children.push(newMenu)
        return
      }
      if (menu.children && addMenu(menu.children, newMenu)) {
        return
      }
    }
  }
  
  function handleStatusChange(row) {
    ElMessage.success(`已${row.status ? '启用' : '禁用'} ${row.title}`)
  }
  </script>
  
  <style scoped>
  .app-container {
    padding: 20px;
  }
  .mr-2 {
    margin-right: 8px;
  }
  .mb-4 {
    margin-bottom: 1rem;
  }
  </style>
